package com.smartthinking.CICPNL.home.activity;

import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Hashtable;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.smartthinking.CICPNL.R;
import com.smartthinking.CICPNL.R.id;
import com.smartthinking.CICPNL.home.activity.Eventos.Eventos_Adapter;
import com.smartthinking.CICPNL.home.objects.App_ImageLoader;

public class ProgramaSocial extends Activity {

	public int Cont = 1;
	public static ArrayList<Dictionary<String,String>> Banners = null;
	public static ArrayList<Dictionary<String,String>> Splash = null;
	public static ArrayList<Dictionary> Actividades = null;
	public Dialog progressDialog;
	public Gallery gallery1;
	public Eventos_Adapter myAdapter;
	public App_ImageLoader imageLoader;

	private Dictionary dic = null;
	public ListView list;
	public Hoteles_Adapter adapter;

	private String sFecha = "-";
	private Intent intent;
	public static ArrayList<Dictionary<String,String>> TraeDatos = null;
	public static ArrayList<Dictionary<String,String>> TraeDatos2 = null;
	public int EVEIDR;
	public TextView txtbusqueda;
	
	String busqueda = "";
	boolean favoritos = false;
	boolean inicial = true;
	Utilities util;

	public void voidFinish(View V) {
		finish();
	}

	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Checks the orientation of the screen
	}

	public void abrirMenuLateral(View V) {
		intent = new Intent(ProgramaSocial.this, MenuLateral.class);
		startActivity(intent);
	}

	@Override
	public void onBackPressed() {
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.ui_programa_social);

		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		EVEIDR = Utilities.EVE_IDR;
		TextView titulo = (TextView) findViewById(R.id.tv_listView_Titulo);
		titulo.setText(R.string.st_programa_social);
		txtbusqueda = (TextView) this.findViewById(id.et_buscar_buscar);
		
		util = new Utilities();
    	EditText txtbusc = (EditText) findViewById(id.et_buscar_buscar);
    	txtbusc.setOnEditorActionListener(new OnEditorActionListener() {
    		@Override
    		public boolean onEditorAction(TextView v, int keyCode, KeyEvent event) {
    			if (event != null&& (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
        		    InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        		    in.hideSoftInputFromWindow(v.getApplicationWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
        			buscar();
        			return true;
    			}
    			return false;
    		}
    	});
		
		CargarContenido();
	}
	
	private void CargarContenido() {
		// TODO Auto-generated method stub
		new AsyncContenido().execute("");
	}
	
	private class AsyncContenido extends AsyncTask<String, String, String>{
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog = ProgressDialog.show(ProgramaSocial.this, "",getString(R.string.st_cargando_));

		}

		@Override
		protected String doInBackground(String... params) {
			String strFavoritos = "";
		    if (favoritos) {
		        strFavoritos = util.getFavoritos(ProgramaSocial.this,"EVENTOSOC");
		        if (strFavoritos.length()>0) {
		            strFavoritos = "and evs_idr in("+strFavoritos+")";
		        }else{
		            strFavoritos = "and evs_idr in(9999999)";
		        }
		    }
		    
		    String qry="";
		    if (busqueda.length()<=0) {
		    	qry = "select evs_idr, evs_fecha, evs_inicio, evs_fin, evs_lugar, evs_titulo, evs_titulo_en, evs_lugar_en, evs_tipo, evs_tipo_en from eventos_sociales where eve_idr=" + EVEIDR  +
		    			" " + strFavoritos + " order by evs_fecha, evs_inicio, evs_lugar";
		    }else{
				 qry = "select evs_idr, evs_fecha, evs_inicio, evs_fin, evs_lugar, evs_titulo, evs_titulo_en, evs_lugar_en, evs_tipo, evs_tipo_en from eventos_sociales  " +
						" where eve_idr=" + EVEIDR +
						" and upper(evs_titulo) like upper('%" + busqueda + "%') " + strFavoritos + 
						" order by evs_fecha, evs_inicio, evs_lugar";
		    }    

			TraeDatos2 = Utilities.qry2(getApplicationContext(), qry);
			
			//BANNERS Y SPLASH
			if(inicial){
				qry = "select a.* from eventos_banners a inner join banners_catalogo b on a.ban_idr = b.ban_idr where a.eve_idr = "+EVEIDR+" and b.ban_nombre in ('BANNER PROGRAMASOC 1','BANNER PROGRAMASOC 2','BANNER PROGRAMASOC 3') ORDER BY b.ban_nombre";
				Banners = Utilities.qry2(getApplicationContext(), qry);
				
				qry = "select a.* from eventos_banners a inner join banners_catalogo b on a.ban_idr = b.ban_idr where a.eve_idr = "+EVEIDR+" and b.ban_nombre = 'SPLASH PROGRAMASOC' ORDER BY b.ban_nombre";
				Splash = Utilities.qry2(getApplicationContext(), qry);
			}
			
			return null;
		}
		
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			
			//acomodo banners
			TraeDatos = new ArrayList<Dictionary<String,String>>();
			Dictionary<String, String> dic = null;
			String encabezado = "";
			int intRenglon = 0;
			int intBanner = 0;
		    for (int i=0; i<TraeDatos2.size(); i++) {
		    	String fecha = TraeDatos2.get(i).get("evs_fecha").toString();
		    	if(!encabezado.equals(fecha)){
		    		encabezado = fecha;
		    		dic = new Hashtable<String, String>();
				    dic.put("Header", encabezado);
				    TraeDatos.add(dic);
		    	}
		    	TraeDatos.add(TraeDatos2.get(i));
		        
		        if (Banners.size()>0) {
		            if (intRenglon==0) {
		                TraeDatos.add(Banners.get(intBanner));
		                if (intBanner==0) {
		                    if (Banners.size()>1) {intBanner++;}else{intBanner=0;}
		                } else if (intBanner==1) {
		                    if (Banners.size()>2) {intBanner++;}else{intBanner=0;}
		                } else if (intBanner==2) {
		                    intBanner=0;
		                }
		            }
		        }
		        if (intRenglon==2) {intRenglon=0;} else {intRenglon++;}
		    }
			
			progressDialog.dismiss();
			
		    //presento splash
		    if(inicial){
		    	inicial = false;
		    	if(Splash.size()>0){
			    	dic = Splash.get(0);
			    	String strPoster = dic.get("ban_url").toString();
				    String strTimer = dic.get("ban_timer").toString();
				    String strPatrocinador = dic.get("pat_idr").toString();
				    if (strPoster.equals("null")) {
				        strPoster = "";
				    }
				    if(strPoster.length()>0){
						intent = new Intent(ProgramaSocial.this, Splash2.class);
						Bundle bund = new Bundle();
						bund.putString("PUT_IMG",strPoster);
						bund.putString("PUT_PAT",strPatrocinador);
						bund.putString("PUT_TIME",strTimer);
						intent.putExtras(bund);
						startActivity(intent);
				    }
			    }
		    }//splash
		    
			Resources res = getResources();
			ListView listView = (ListView) findViewById(id.list);
			ProgramaSocialArrayAdapter adapter = new ProgramaSocialArrayAdapter(ProgramaSocial.this, TraeDatos, res.getString(R.string.QRY_SERVLET));
			listView.setAdapter(adapter);
			
			listView.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
					muestra_detalle(position);
				}
			});
		}
	}

	
	private void muestra_detalle(int  x){
		Dictionary<String,String> dic = TraeDatos.get(x);
		String ban = dic.get("pat_idr");
		String evs = dic.get("evs_idr");
		
		if(evs != null){
			intent = new Intent(this, ProgramaSocDetalle.class);
			Bundle bund = new Bundle();
			bund.putString("idevs",evs);
			intent.putExtras(bund);
			startActivity(intent);
		}else if(ban != null){
			intent = new Intent(this, PatrocinadoresDetalle.class);
			Bundle bund = new Bundle();
			bund.putString("idpatrocinador",ban);
			intent.putExtras(bund);
			startActivity(intent);
		}
	}

	public class Hoteles_Adapter extends BaseAdapter {

		private LayoutInflater inflater = null;
		private ArrayList<Dictionary> data;

		public Hoteles_Adapter(ArrayList<Dictionary> d) {

			data = d;
			inflater = (LayoutInflater) ProgramaSocial.this
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			imageLoader = new App_ImageLoader(
					ProgramaSocial.this.getApplicationContext());

		}

		public int getCount() {
			return data.size();
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public class ViewHolder {

			public TextView tvTitulo;
			public TextView tvSubtitulo;
			public TextView tvHora;

			public TextView tvFecha;

			public ImageView fondorojo;
			// public ImageView vermas;

			public ImageView banner;

		}

		public View getView(int position, View convertView, ViewGroup parent) {

			View vi = convertView;
			ViewHolder holder;

			if (convertView == null) {

				vi = inflater.inflate(R.layout.ui_programa_items, null);

				holder = new ViewHolder();
				holder.tvTitulo = (TextView) vi.findViewById(R.id.tv_programa_items_titulo);
				holder.tvSubtitulo = (TextView) vi.findViewById(R.id.tv_programa_items_salon);
				holder.tvHora = (TextView) vi.findViewById(R.id.tv_programa_items_hora);

				// @+id/iv_listview_items_imagen
				// holder.icon = (ImageView) vi
				// .findViewById(id.iv_listview_items_imagen);

				holder.banner = (ImageView) vi.findViewById(id.iv_programa_items_banner);
				holder.fondorojo = (ImageView) vi.findViewById(id.imageView2);
				//holder.tvFecha = (TextView) vi.findViewById(id.tv_programa_item_fecha);

				// holder.vermas = (ImageView)
				// vi.findViewById(id.iv_items_vermas);

				vi.setTag(holder);

			} else

				holder = (ViewHolder) vi.getTag();

			/** Insert banner **/
			// ActividadesBanner.add(BannersHoteles.get(0));
			// ban_url

			if (data.get(position).get("ban_url") != null) {
				holder.tvTitulo.setText("");
				holder.tvSubtitulo.setText("");
				holder.tvHora.setText("");
				holder.tvFecha.setText("");
				holder.fondorojo.setVisibility(holder.fondorojo.INVISIBLE);

				try {
					holder.banner.setVisibility(holder.banner.VISIBLE);

					String url_img = getString(R.string.QRY_URL_IMG)
							+ data.get(position).get("ban_url").toString()
									.replace(" ", "%20");

					holder.banner.setTag(url_img);

					imageLoader.DisplayImage(url_img, ProgramaSocial.this,holder.banner);
					// holder.icon.setVisibility(holder.icon.GONE);
					// holder.vermas.setVisibility(holder.vermas.GONE);

				} catch (Exception ex) {

					String s = ex.getMessage().toString();

				}

			} else {

				holder.banner.setVisibility(holder.banner.GONE);
				//
				// holder.icon.setVisibility(holder.icon.VISIBLE);
				//
				// holder.vermas.setVisibility(holder.vermas.VISIBLE);

				if (position == 0) {
					try {

						sFecha = data.get(position).get("nen_fecha").toString();

						holder.fondorojo
								.setVisibility(holder.fondorojo.VISIBLE);
						holder.tvFecha.setText(sFecha);
					} catch (Exception e) {
					}
				} else {
					if (sFecha.equals(data.get(position).get("nen_fecha")
							.toString())) {

						holder.tvFecha.setText("");
						holder.fondorojo
								.setVisibility(holder.fondorojo.INVISIBLE);

					} else {

						try {
							sFecha = data.get(position).get("nen_fecha")
									.toString();

							holder.fondorojo
									.setVisibility(holder.fondorojo.VISIBLE);
							holder.tvFecha.setText(sFecha);
						} catch (Exception e) {

						}
					}
				}

				try {
					String Titulo = data.get(position).get("nen_titulo")
							.toString();

					holder.tvTitulo.setText(Titulo);
				} catch (Exception e) {

				}
				try {
					String Hora = data.get(position).get("nen_inicio")
							.toString();
					holder.tvHora.setText(Hora);
				} catch (Exception e) {

				}
				try {
					String Salon = data.get(position).get("nen_lugar")
							.toString();
					holder.tvSubtitulo.setText(Salon);
				} catch (Exception e) {

				}
			}

			return vi;

		}
	}

	public void fFavoritos(View v){
		Button btnf = (Button) findViewById(R.id.iv_btn_favoritos);
		Button btnt = (Button) findViewById(R.id.iv_btn_todos);
		if (favoritos){
			btnf.setBackgroundResource(R.drawable.lst_btn_favoritos_des);
			btnt.setBackgroundResource(R.drawable.lst_btn_todos_act);
			favoritos = false;
		}else{
			btnf.setBackgroundResource(R.drawable.lst_btn_favoritos_act);	
			btnt.setBackgroundResource(R.drawable.lst_btn_todos_des);
			favoritos = true;
		}
		CargarContenido();
	}	
	
	public void detalle(View v){
		intent = new Intent(this, ProgramaSocDetalle.class);
		startActivity(intent);
	}
	
	public void borrar(View v){
		EditText txtbusc = (EditText) findViewById(id.et_buscar_buscar);
		txtbusc.setText("");
		buscar();
	}
	
	public void buscar(){
		String strBusqueda = ((EditText) findViewById(id.et_buscar_buscar)).getText().toString().trim();
		if(!strBusqueda.equals(busqueda)){
			busqueda = strBusqueda;
			CargarContenido();
		}
	}
	
	public void voidbusqueda(View v){
    	InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        buscar();
	}
	
}
